import { globby } from 'globby';
import fs from 'fs';
import path from 'path';
import { transformAsync } from '@babel/core';
 
const SRC_DIR = './src';
const DEST_DIR = './dist';
 
const isClassTransformable = (code) => {
  const patterns = [
    /function\s+\w+\s*\([^)]*\)\s*\{[^}]*this\.[^}]+\}/,
    /\.prototype\.\w+\s*=\s*function/g 
  ];
  return patterns.some(p  => p.test(code));  
};
 
async function transformFiles() {
  const files = await globby(['**/*.js'], { cwd: SRC_DIR });
 
  for (const file of files) {
    const srcPath = path.join(SRC_DIR,  file);
    const destPath = path.join(DEST_DIR,  file);
    const code = fs.readFileSync(srcPath,  'utf-8');
 
    if (!isClassTransformable(code)) {
      console.warn(`⏩  跳过不可转换文件: ${file}`);
      continue;
    }
 
    const result = await transformAsync(code, {
      filename: srcPath,
      presets: [], // 禁用preset-env避免干扰 
      plugins: [
        ['@babel/plugin-transform-classes', { 
          loose: false,
          assumptions: {
            setClassMethods: true,
            setComputedProperties: true 
          }
        }]
      ]
    });
 
    // 结果验证 
    // if (!result.code.includes('class  ') && isClassTransformable(code)) {
    //   console.error(`❌  转换失败: ${file}`, result.code); 
    //   process.exit(1); 
    // }
 
    fs.mkdirSync(path.dirname(destPath),  { recursive: true });
    fs.writeFileSync(destPath,  result.code); 
    console.log(`✅  已转换: ${file}`, result.code.split('\n')[0]); 
  }
}
 
transformFiles().catch(console.error); 